// listenerManager.js
const GroupMessageListener = require('../GroupMessageListener');

const MAXSIZE = 20;
const listenes = [];  // 监听列表

/**
 * 添加监听群组
 * @param {Object} listene - { id, title, accessHash, listenerClient, ... }
 */
async function addListenes(listene) {
  if (listenes.length >= MAXSIZE) {
    return '监听组已经达最大监听数量';
  }

  const exists = listenes.find(item => item.id.toString() === listene.id.toString());
  if (exists) {
    return '此群组已经添加监听';
  }

  listenes.push(listene);
  return '添加成功';
}

/**
 * 删除监听群组（会先停止对应监听器）
 * @param {string|number} id 群组ID
 */
async function delListenes(id) {
  const index = listenes.findIndex(item => item.id.toString() === id.toString());
  if (index !== -1) {
    // 先停止监听器，释放事件绑定
    await listenes[index].listenerClient.stop();
    listenes.splice(index, 1);
    return '删除成功';
  } else {
    return '未找到指定监听项';
  }
}

/**
 * 获取所有监听群组信息
 * @returns {Array}
 */
function getListenes() {
  return listenes.map(item => ({
    id: item.id.toString(),
    title: item.title,
    accessHash: item.accessHash.toString(),
    state: item.listenerClient.isListening()
  }));
}

/**
 * 启动指定群组监听
 * @param {GroupMessageListener} listenerClient 
 */
async function listenerStart(listenerClient) {
  if (!listenerClient.isListening()) {
    await listenerClient.start(async (msg, sender) => {
      if (!msg) return;
      console.log(`📨 来自 ${sender.id} 的消息：${msg}`);
    });
  } else {
    console.log(`监听器 ${listenerClient.channelId} 已经在运行中`);
  }
}

/**
 * 停止监听
 * @param {GroupMessageListener} listenerClient 
 */
async function listenerStop(listenerClient) {
  if (listenerClient.isListening()) {
    await listenerClient.stop();
  } else {
    console.log(`监听器 ${listenerClient.channelId} 未运行`);
  }
}

/**
 * 根据群组ID获取对应监听器
 * @param {string|number} id 
 * @returns {GroupMessageListener | null}
 */
function getListenerClientById(id) {
  const target = listenes.find(item => item.id.toString() === id.toString());
  return target ? target.listenerClient : null;
}

module.exports = {
  getListenerClientById,
  listenerStop,
  listenerStart,
  addListenes,
  delListenes,
  getListenes,
};
